﻿@page "/System/UploadDemo"
@inject ToastService ToastService
@inject DownloadService DownloadService
@implements IDisposable

<CardUpload TValue="string" IsSingle="true" OnChange="@OnCardUpload" OnDelete="@(fileName => Task.FromResult(true))"></CardUpload>
<Button IsAsync="true" Icon="fa-solid fa-download" Text="下载" OnClickWithoutRender="DownloadPhysicalFileAsync"></Button>


@code {
    private CancellationTokenSource? ReadToken { get; set; }

    /// <summary>
    /// Dispose
    /// </summary>
    public void Dispose()
    {
        ReadToken?.Cancel();
        GC.SuppressFinalize(this);
    }

    private static long MaxFileLength => 200 * 1024 * 1024;

    private async Task OnCardUpload(UploadFile file)
    {
        if (file != null && file.File != null)
        {
            // 服务器端验证当文件大于 2MB 时提示文件太大信息
            if (file.Size > MaxFileLength)
            {
                file.Code = 1;
                file.Error = "文件太大";
            }
            else
            {
                await SaveToFile(file);
            }
        }
    }

    private async Task<bool> SaveToFile(UploadFile file)
    {
        var ret = false;
        var uploaderFolder = Path.Combine(Application.wwwrootPath, $"Upload\\10302");
        var fileName = Path.Combine(uploaderFolder, file.OriginFileName);
        file.FileName = fileName;
        ReadToken ??= new CancellationTokenSource();
        ret = await file.SaveToFileAsync(fileName, MaxFileLength, ReadToken.Token);

        if (ret)
        {
            // 保存成功
            file.PrevUrl = fileName;
        }
        else
        {
            var errorMessage = $"上传错误 {file.OriginFileName}";
            file.Code = 1;
            file.Error = errorMessage;
            await ToastService.Error("上传错误", errorMessage);
        }
        return ret;
    }

    private async Task DownloadPhysicalFileAsync()
    {
        try
        {
            var filePath = Path.Combine(Application.wwwrootPath, "Upload\\10302\\active_desktop.dll");
            await using var stream = File.OpenRead(filePath);
            await DownloadService.DownloadFromStreamAsync("active_desktop_render.dll", stream);
        }
        catch (FileNotFoundException msg)
        {
            await ToastService.Error("下载", msg.Message);
        }
    }

}
